<?php
session_start();

// 题目列表
$words = [
    "苹果",
    "香蕉",
    "汽车",
    "飞机",
    "篮球"
];

// 如果没有当前题目，随机选择一个
if (!isset($_SESSION['current_word'])) {
    $_SESSION['current_word'] = $words[array_rand($words)];
    $_SESSION['attempts'] = 0;
}

// 处理用户猜测
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $guess = $_POST['guess'];
    $_SESSION['attempts']++;

    if ($guess === $_SESSION['current_word']) {
        $result = [
            'correct' => true,
            'message' => "猜对啦！你一共用了 {$_SESSION['attempts']} 次尝试。",
        ];
        // 重置题目
        $_SESSION['current_word'] = $words[array_rand($words)];
        $_SESSION['attempts'] = 0;
    } else {
        $result = [
            'correct' => false,
            'message' => "猜错了，请继续尝试。",
        ];
    }

    header('Content-Type: application/json');
    echo json_encode($result);
}
?>